import 'package:flutter/material.dart';
import 'package:flutter_deer/game/page/game_page.dart';
import 'package:flutter_deer/index/page/index_page.dart';
import 'package:flutter_deer/home/provider/home_provider.dart';
import 'package:flutter_deer/mvp/base_page.dart';
import 'package:flutter_deer/res/resources.dart';
import 'package:flutter_deer/setting/iview/version_iview.dart';
import 'package:flutter_deer/setting/models/version_entity.dart';
import 'package:flutter_deer/setting/presenter/version_presenter.dart';
import 'package:flutter_deer/setting/provider/version_provider.dart';
import 'package:flutter_deer/setting/widgets/update_dialog.dart';
import 'package:flutter_deer/shop/page/shop_page.dart';
import 'package:flutter_deer/indent/page/indent_page.dart';
import 'package:flutter_deer/util/theme_utils.dart';
import 'package:flutter_deer/widgets/double_tap_back_exit_app.dart';
import 'package:flutter_deer/widgets/load_image.dart';
import 'package:motion_tab_bar/MotionTabBar.dart';
import 'package:motion_tab_bar/MotionTabBarController.dart';
import 'package:package_info/package_info.dart';
import 'package:flutter_gen/gen_l10n/deer_localizations.dart';
import 'package:provider/provider.dart';

class Main extends StatefulWidget {
  const Main({super.key});

  @override
  _MainState createState() => _MainState();
}

class _MainState extends State<Main>
    with
        SingleTickerProviderStateMixin,
        RestorationMixin,
        BasePageMixin<Main, VersionPresenter>
    implements VersionIMvpView {
  late List<Widget> _pageList;
  List<String> _appBarTitles = [];
  final PageController _pageController = PageController();
  MotionTabBarController? _motionTabBarController;
  @override
  VersionPresenter createPresenter() => VersionPresenter();
  HomeProvider provider = HomeProvider();

  VersionProvider versionProvider = VersionProvider();

  @override
  void setVersion(VersionEntity? entity) {
    versionProvider.setVersion(entity);
    PackageInfo.fromPlatform().then((PackageInfo packageInfo) {
      if (packageInfo.version != entity!.versionNum) {
        Future.delayed(
            Duration(seconds: 10),
            () => {
                  showDialog<void>(
                      context: context,
                      barrierDismissible: false,
                      builder: (_) => UpdateDialog(versionEntity: entity))
                });
      }
    });
  }

  @override
  void initState() {
    super.initState();
    _motionTabBarController = MotionTabBarController(
      initialIndex: 0,
      length: 3,
      vsync: this,
    );
    initData();
  }

  @override
  void dispose() {
    _pageController.dispose();
    _motionTabBarController!.dispose();
    super.dispose();
  }

  void initData() {
    _pageList = [
      const IndexPage(),
      const IndentPage(),
      const ShopPage(),
    ];
  }

  @override
  Widget build(BuildContext context) {
    _appBarTitles = [
      DeerLocalizations.of(context)!.tabHome,
      DeerLocalizations.of(context)!.tabQuery,
      DeerLocalizations.of(context)!.tabMe
    ];

    final bool isDark = context.isDark;
    return ChangeNotifierProvider<HomeProvider>(
      create: (_) => provider,
      child: DoubleTapBackExitApp(
        child: Scaffold(
            bottomNavigationBar: Consumer<HomeProvider>(
              builder: (_, provider, __) {
                return MotionTabBar(
                  controller: _motionTabBarController,
                  textStyle: TextStyle(
                      fontWeight: FontWeight.bold,
                      color: isDark
                          ? Colours.dark_text
                          : Theme.of(context).primaryColor),
                  tabBarColor: context.backgroundColor,
                  tabIconColor:
                      isDark ? Colors.white : Theme.of(context).primaryColor,
                  tabIconSize: 21,
                  tabIconSelectedSize: 26,
                  tabIconSelectedColor: Colors.white,
                  tabSelectedColor: isDark
                      ? Colours.dark_bg_gray
                      : Theme.of(context).primaryColor,
                  initialSelectedTab: _appBarTitles[0],
                  labels: _appBarTitles,
                  icons: const [
                    Icons.home_filled,
                    Icons.query_stats,
                    Icons.person
                  ],
                  onTabItemSelected: (int value) {
                    setState(() {
                      _motionTabBarController!.index = value;
                      _pageController.jumpToPage(value);
                      provider.notifyListeners();
                    });
                  },
                );
              },
            ),
            // 使用PageView的原因参看 https://zhuanlan.zhihu.com/p/58582876
            body: PageView(
              physics: NeverScrollableScrollPhysics(), // 禁止滑动
              controller: _pageController,
              onPageChanged: (int index) => provider.setIndex(index),
              children: _pageList,
            )),
      ),
    );
  }

  @override
  String? get restorationId => 'main';

  @override
  void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
    registerForRestoration(provider, 'BottomNavigationBarCurrentIndex');
  }
}
